package com.example.chat.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson.JSON;
import com.example.chat.user.WeChatUser;
import com.example.chat.utils.WechatUtil;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.jackson.JsonComponentModule;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin(origins = "http://localhost:8080")
public class WxCheckController {
    private static final Logger log = LoggerFactory.getLogger(WxCheckController.class);

    private final Map<String, String> map = new HashMap<>();
    private final JsonComponentModule jsonComponentModule;

    public WxCheckController(JsonComponentModule jsonComponentModule) {
        this.jsonComponentModule = jsonComponentModule;
    }

    @GetMapping("/wxCheck")
    public String check(
            @RequestParam(value = "signature") String signature,
            @RequestParam(value = "timestamp") String timestamp,
            @RequestParam(value = "nonce") String nonce,
            @RequestParam(value = "echostr") String echostr
    ) {
        // 直接返回微信的 echostr 参数
        return echostr;
    }

//第一步：用户同意授权，获取code
    @GetMapping(value = "/wxLogin")
    public void wxLoginPage( HttpServletResponse response) throws Exception {

        //redirect_uri是回调的地址 注意要转成UrlEncode格式
        String redirect_uri = URLEncoder.encode("http://5h82ie.natappfree.cc/wxCallback", "utf-8");
        String appid = "wx0135051b38c87795";
        String url1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_userinfo&STATE=#wechat_redirect";
        //生成二维码，扫描后跳转上面的地址
        log.info("生成二维码");
        response.setContentType("image/png");

        QrConfig qrConfig = new QrConfig(400, 400);
        qrConfig.setErrorCorrection(ErrorCorrectionLevel.L);
        QrCodeUtil.generate(url1, qrConfig, "jpg", response.getOutputStream());

    }
    //第二步：通过code换取网页授权access_token
    @RequestMapping(value = "/wxCallback")
    @ResponseBody
    public String wxCallback(String code,String state,HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {

        // 使用工具类获取用户信息
        WeChatUser user = WechatUtil.getUserInfo(code);

        // 将用户信息转换为JSON字符串返回
        return JSON.toJSONString(user);
    }

}





